package tv_megazineplus

import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.DefaultValue
import javax.ws.rs.core.Response
import org.codehaus.groovy.runtime.TimeCategory

@Path('/api/getTokenToAlert')
class GetTokenToAlertResource {
        def sendMailService
        def sendSmsService
    @GET
    //@Produces('text/plain')
    Response getGetTokenToAlertRepresentation(
        @QueryParam('userEmail') String email,
        @DefaultValue("false") @QueryParam('sendByMail') String opcao) {
        def t1 = System.currentTimeMillis()
      
        if(email==null){
           return Response.status(400).build();
        }
        //email=xxx@sapo.pt?email=true
        
        def error = null
        def operacao
        def existe = Users.findByEmail(email)
        if(opcao == null||opcao != 'true'){ // email é nulo
            operacao = 'sms'
        }else{ // email e especificado
            if(opcao == 'true'){ // email true
                operacao = 'email'
            }
             }
        if(existe && error == null){
            ////////////////////////// SEND TOKEN HERE
            def ramdomNumber = ramdom(8)
            use(TimeCategory){
                new Token(user: existe, token: ramdomNumber, expira: new Date() + 30.minutes).save() 
            }//Users é o existe
                
            def sms = 'O seu token de acesso provisório (30min) é: ' + ramdomNumber             
                
            if(operacao == 'email'){
                sendMailService.serviceMethod(existe.email, 'TvMg+ Token de Acesso', sms)
            }
            
            if(operacao == 'sms'){
                sendSmsService.serviceMethod('TvMgP', existe.phoneNumber, sms)
            }
            def tt = System.currentTimeMillis() - t1       
            new Statistic(servico: Servicos.findByName('getTokenToAlert'), totalTime: tt, date: new Date()).save()
            return Response.ok("sucess").build();
            //////////////////////////////////////////
            
                
        }else{ // render error
                
          return Response.status(400).build();
		}	
         
        
return error
    }
        
    def ramdom (nnn){
        def num = 10 * nnn
        Random random = new Random()
        random.nextInt(10 * num)
    }
}
